package com.taotao.admin.rest;

import com.rop.client.CompositeResponse;
import com.taotao.admin.DefaultRopClient;
import com.taotao.admin.MyRopClient;
import com.taotao.admin.pojo.ManagerUI;
import com.taotao.rop.database.Constant;
import com.taotao.rop.database.domain.BaseDomain;
import com.taotao.rop.database.domain.Manager;
import com.taotao.rop.database.domain.Role;
import com.taotao.rop.response.BaseResponse;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.LinkedHashMap;
import java.util.List;

@Controller
@RequestMapping(value = "/admin")
public class LoginController {
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public Object login(HttpServletRequest request) throws UnsupportedEncodingException {
        request.setCharacterEncoding("UTF-8");

        String code = request.getParameter("code");
        String trueCode = request.getSession().getAttribute("vcode").toString();
        if (!code.equalsIgnoreCase(trueCode)) {
            return "{" + "\"success\":false,\"message\":\"验证码有误\"}";
        }

        Manager ropRequest = new Manager();
        ropRequest.setName(request.getParameter("userName"));
        ropRequest.setPassword(request.getParameter("password"));
        ropRequest.setStatus(Constant.STATUS_ENABLE);

        CompositeResponse response = MyRopClient.getRopClient("").buildClientRequest()
                .post(ropRequest, BaseResponse.class, "manager.logon", "1.0");

        if (response.isSuccessful()) {
            return response.getSuccessResponse();
        } else {
            return response.getErrorResponse();
        }
    }

    @RequestMapping(value = "/session", method = RequestMethod.POST)
    @ResponseBody
    public Object getSession(HttpServletRequest request) throws UnsupportedEncodingException {
        request.setCharacterEncoding("UTF-8");
        String sessionId = request.getHeader("sessionId");
        DefaultRopClient client = MyRopClient.getRopClient(sessionId);

        CompositeResponse<BaseResponse> response = client.buildClientRequest()
                .post(new BaseDomain(), BaseResponse.class, "manager.session", "1.0");
        if (response.isSuccessful()){
            BaseResponse resp = response.getSuccessResponse();
            if (resp.getSuccess()) {
                ManagerUI managerUI = new ManagerUI();
                managerUI.setSessionId(sessionId);
                LinkedHashMap<String, Object> data = (LinkedHashMap<String, Object>) resp.getData();
                managerUI.setManagerId(Long.parseLong(data.get("managerId").toString()));
                managerUI.setRoleId(Long.parseLong(data.get("roleId").toString()));
                managerUI.setAppId(data.get("appId").toString());

                Manager manager = new Manager();
                manager.setId(Long.parseLong(data.get("managerId").toString()));
                CompositeResponse respManager = client.buildClientRequest()
                        .post(manager, BaseResponse.class, "manager.find", "1.0");
                if (respManager.isSuccessful()) {
                    BaseResponse baseRespManager = (BaseResponse) respManager.getSuccessResponse();
                    if (baseRespManager.getSuccess()) {
                        List<LinkedHashMap> managerList = (List<LinkedHashMap>) baseRespManager.getData();
                        if (managerList != null && managerList.size() > 0) {
                            managerUI.setManagerName(managerList.get(0).get("name").toString());
                        }
                    }
                }

                Role role = new Role();
                role.setId(Long.parseLong(data.get("roleId").toString()));
                CompositeResponse respRole = client.buildClientRequest()
                        .post(role, BaseResponse.class, "role.list", "1.0");
                if (respRole.isSuccessful()) {
                    BaseResponse baseRespRole = (BaseResponse) respRole.getSuccessResponse();
                    if (baseRespRole.getSuccess()) {
                        List<LinkedHashMap> roleList = (List<LinkedHashMap>) baseRespRole.getData();
                        if (roleList != null && roleList.size() > 0) {
                            managerUI.setRoleName(roleList.get(0).get("name").toString());
                            if (roleList.get(0).get("roleLevel") != null
                                    && StringUtils.isNumeric(roleList.get(0).get("roleLevel").toString())) {
                                managerUI.setRoleLevel(Integer.parseInt(roleList.get(0).get("roleLevel").toString()));
                            }
                        }
                    }
                }

                return managerUI;
            } else {
                return resp;
            }
        } else {
            return response.getErrorResponse().getSubErrors().get(0);
        }
    }

    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    @ResponseBody
    public Object logout(HttpServletRequest request) throws UnsupportedEncodingException {
        request.setCharacterEncoding("UTF-8");

        CompositeResponse response = MyRopClient.getRopClient(request.getHeader("sessionId")).buildClientRequest()
                .post(new BaseDomain(), BaseResponse.class, "manager.logout", "1.0");

        if (response.isSuccessful()) {
            return response.getSuccessResponse();
        } else {
            return response.getErrorResponse().getSubErrors().get(0);
        }
    }
}
